<?php

namespace app\store\model;

use app\common\model\Video as VideoModel;
use app\common\model\VideoQuestion as VideoQuestionModel;
class Video extends VideoModel
{
    /**
     * 获取视频列表（分页）
     * @param int $pageSize 每页显示条数
     * @param array $param 查询参数
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($pageSize = 10, $param = [])
    {
        $domain = request()->domain(); // 动态获取当前域名

        $query = $this->alias('video')
            ->field([
                'video.*',
                'CONCAT("' . $domain . '/uploads/", uf.file_name) as video_img_url' // 拼接完整路径
            ])
            ->join('upload_file uf', 'video.video_img = uf.file_id', 'LEFT') // 关联 upload_file 表
            ->where('video.is_delete', '=', 0) // 过滤未删除的问卷
            ->order(['video.video_sort' => 'asc', 'video.create_time' => 'desc']); // 排序规则

        // 如果存在搜索参数且不为空，则添加模糊搜索条件
        if (!empty($param['search'])) {
            $query->where('video.video_title', 'like', '%' . trim($param['search']) . '%');
        }

        // 返回分页数据
        return $query->paginate($pageSize);
    }

    /* 新增记录
    * @param array $data
    * @return false|int
    */
    public function add($data)
    {
        // 检查并清理数据
        if (!isset($data['video_title']) || empty($data['video_title'])) {
            $this->error = '标题不能为空';
            return false;
        }
        // 检查并清理数据
        if (!isset($data['video_url']) || empty($data['video_url'])) {
            $this->error = '视频链接不能为空';
            return false;
        }
        // 检查并清理数据
        if (!isset($data['video_img']) || empty($data['video_img'])) {
            $this->error = '视频封面不能为空';
            return false;
        }
        $data['wxapp_id'] = self::$wxapp_id;
        // 插入记录
        return $this->allowField(true)->save($data);
    }
    /**
     * 更新记录
     * @param $data
     * @return bool|int
     */
    public function edit($data)
    {
        // dump($data);die;
        return $this->save($data, ['video_id' => $data['video_id']]);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 获取问卷总数量
     * @param array $where
     * @return int|string
     */
    public static function getTotal($where = [])
    {
        $model = new static;
        !empty($where) && $model->where($where);
        return $model->where('is_delete', '=', 0)->count();
    }
    /**
     * 定义问卷和问题的一对多关联
     */
    public function questions()
    {
        return $this->hasMany('app\store\model\VideoQuestion', 'Video_id', 'id')->where("is_delete","0")
                    ->with(['options']); // 关联每个问题的选项
    }
}